<template>
    <div class="login_wrap">
        <div class="login_header">
            <i class="el-icon-arrow-left" @click="handleBack"></i>
        </div>
        <div class="logo">
            <img src="../../assets/img/demi@2x.png" alt="">
        </div>
        <div class="form">
            <div class="phone">
                <div class="phone_icon">
                    <img src="../../assets/img/phone@2x.png" alt="">
                </div>
                <el-input v-model="phone" placeholder="请输入手机号" @input="changePhone"></el-input>
            </div>
            <div class="yzm">
                <div class="yzm_input">
                    <div style="align-self: center">
                        <img class="yzm_icon" src="../../assets/img/verification_code@2x.png" alt="">
                    </div>
                    <el-input v-model="yzm" placeholder="验证码"></el-input>
                </div>
                <p @click="handleRule" v-text="success ? timeText : '获取验证码'"></p>
            </div>
        </div>
        <div class="submit">
            <el-button type="primary" @click="login">登录</el-button>
        </div>
        <div class="bottom">
            <p>
                登录即代表您同意“招聘app”的<span @click="handleAgreement">服务和隐私条款</span>
            </p>
        </div>
        <div class="agreement">
            <el-dialog
                    title="服务和隐私条款"
                    :visible.sync="Agreement"
                    width="90%">
                <agreement></agreement>
            </el-dialog>
        </div>

    </div>
</template>

<script>
    import {getToken} from '../../libs/http';
    import http from '../../libs/http';
    import agreement from '../../components/xieyi'

    export default {
        name: 'index',
        components: {agreement},
        data() {
            return {
                phone: '',
                yzm: '',
                time: 60,
                success: false,
                Agreement: false,
                name: '',
                id: ''
            }
        },
        created() {
            this.getParams();
        },
        computed: {
            timeText: function () {
                setTimeout(function () {
                    this.time = this.time - 1;
                }.bind(this), 1000);
                if (this.time > 0) {
                    return "[ " + this.time + "s ]";
                } else if (this.time <= 0) {
                    this.success = false;
                    this.time = 61;
                    return null;
                }
            }
        },
        methods: {
            getParams() {
                // 取到路由带过来的参数
                this.name = this.$route.query.name;
                this.id = this.$route.query.id;
            },

            handleAgreement() {
                this.Agreement = true
            },

            handleBack() {
                const token = getToken();
                if (!token) {
                    this.$router.push({
                        name: 'index',
                        query: {id: this.id, task_order_id:sessionStorage.getItem('task_order_id')}
                    });
                } else {
                    this.$router.push({
                        name: this.name,
                        query: {id: this.id, task_order_id:sessionStorage.getItem('task_order_id')}
                    });
                }
            },

            changePhone() {
                if (!this.phone) {
                    this.success = false;
                    this.time = 61
                }
            },
            handleRule() {
                if (!this.phone) {
                    this.$message({
                        showClose: true,
                        message: '请输入手机号',
                        type: 'error',
                        duration: 500
                    })
                } else {
                    if (this.time === 60) {
                        this.apiPost('/sms/captcha', {
                            phone: this.phone,
                            mode: 3
                        }).then((res) => {
                            if (res) {
                                this.success = true;
                                this.$message({
                                    showClose: true,
                                    message: '发送成功',
                                    type: 'success',
                                    duration: 500
                                })
                            }

                        })
                    }
                }

            },
            login() {
                this.apiPost('/api/login', {
                    phone: this.phone,
                    mode: 'sms',
                    captcha: this.yzm,
                }).then((res) => {
                    this.yzm = '';
                    this.setToken({authorization: res.token});
                    let user_id = res.user_id;
                    let userSig = res.usersig;
                    let userType = 'a';
                    if (res.type === 2) {
                        userType = 'b'
                    } else {
                        userType = 'a'
                    }
                    if(res.type === 0){
                        this.apiPost('api/user/update',{type:1}).then((res)=>{
                            console.log(res)
                        })
                    }
                    console.log(res);
                    sessionStorage.setItem('userID', user_id + userType);
                    sessionStorage.setItem('userSig', userSig);
                    sessionStorage.setItem('token', res.token);
                    this.tim.login({
                        userID: user_id + userType,
                        userSig: userSig
                    }).then(() => {
                        this.$store.commit('toggleIsLogin', true);
                        this.$store.commit('startComputeCurrent');
                        console.log(this.name);
                        this.$router.push({
                            name: this.name,
                            query: {id: this.id}
                        });
                        this.initListener()
                    }).catch(error => {
                        this.$store.commit('showMessage', {
                            message: '登录失败：' + error.message,
                            type: 'error'
                        })
                    });
                })
            },
            initListener() {
                // 登录成功后会触发 SDK_READY 事件，该事件触发后，可正常使用 SDK 接口
                this.tim.on(this.TIM.EVENT.SDK_READY, this.onReadyStateUpdate, this)
                // SDK NOT READT
                this.tim.on(this.TIM.EVENT.SDK_NOT_READY, this.onReadyStateUpdate, this)
                // 被踢出
                this.tim.on(this.TIM.EVENT.KICKED_OUT, () => {
                    this.$store.commit('showMessage', {
                        message: '被踢出，请重新登录。',
                        type: 'error'
                    })
                    this.$store.commit('toggleIsLogin', false)
                    this.$store.commit('reset')
                })
                // SDK内部出错
                this.tim.on(this.TIM.EVENT.ERROR, this.onError)
                // 收到新消息
                this.tim.on(this.TIM.EVENT.MESSAGE_RECEIVED, this.onReceiveMessage)
                // 会话列表更新
                this.tim.on(this.TIM.EVENT.CONVERSATION_LIST_UPDATED, event => {
                    this.$store.commit('updateConversationList', event.data)
                })
            },
            onReceiveMessage({ data: messageList }) {
                console.log('aaa');
                // this.show = false
                this.handleAt(messageList);
                this.$store.commit('pushCurrentMessageList', messageList)
            },
            onError({ data }) {
                if (data.message !== 'Network Error') {
                    this.$store.commit('showMessage', {
                        message: data.message,
                        type: 'error'
                    })
                }
            },
            onReadyStateUpdate({ name }) {
                const isSDKReady = name === this.TIM.EVENT.SDK_READY ? true : false
                this.$store.commit('toggleIsSDKReady', isSDKReady)

                if (isSDKReady) {
                    this.tim.getMyProfile().then(({ data }) => {
                        this.$store.commit('updateCurrentUserProfile', data)
                    })
                    // this.$store.dispatch('getBlacklist')
                }
            },
            handleAt(messageList) {
                // 筛选有 @ 符号的文本消息
                const atTextMessageList = messageList.filter(
                    message => message.type === this.TIM.TYPES.MSG_TEXT && message.payload.text.includes('@')
                )
                for (let i = 0; i < atTextMessageList.length; i++) {
                    const message = atTextMessageList[i]
                    const matched = message.payload.text.match(/@\w+/g)
                    if (!matched) {
                        continue
                    }
                    // @ 我的
                    if (matched.includes(`@${this.currentUserProfile.userID}`)) {
                        // 当前页面不可见时，调用window.Notification接口，系统级别通知。
                        // if (document.hidden) {
                        //   this.notifyMe(message)
                        // }
                        // Notification({
                        //   title: `有人在群${message.conversationID.slice(5)}提到了你`,
                        //   message: message.payload.text,
                        //   duration: 3000
                        // })
                        this.$bus.$emit('new-messsage-at-me', {
                            data: { conversationID: message.conversationID }
                        })
                    }
                }
            },
        },
        mixins: [http]
    }
</script>

<style lang="stylus">
    .login_wrap
        width 100%;
        height 100%;
        text-align left

        .login_header
            height 44px;
            line-height 44px;
            padding-left 16px

            .el-icon-arrow-left
                font-size 20px

        .logo
            margin 50px 0;
            padding-left 48px

            img
                width 94px;

        .form
            padding 0 48px

            .phone
                display flex;
                padding-bottom 17px
                border-bottom 1px solid #CCCCCC

                .phone_icon
                    align-self center

                    img
                        width 20px;
                        margin-right 15px;

                .el-input
                    align-self center

                    .el-input__inner
                        padding 0;
                        border none;
                        height 27px;
                        font-size 15px;
                        line-height 27px;

            .yzm
                display flex;
                padding-top 22px;
                text-align right;
                justify-content space-between

                .yzm_input
                    display flex
                    align-self center

                    .yzm_icon
                        width 20px;
                        margin-right 15px;

                    .el-input
                        align-self center

                        .el-input__inner
                            padding 0;
                            border none;
                            height 27px;
                            font-size 15px;
                            line-height 27px;

                p
                    font-size 15px;
                    align-self center;
                    white-space: nowrap;
                    color: rgba(36, 191, 255, 1);

        .submit
            padding 43px 30px;

            .el-button
                width 100%
                border 0
                font-size 17px
                border-radius: 25px;
                background: rgba(59, 199, 255, 1);

        .bottom
            left 50%;
            bottom 20px;
            color #999999;
            position fixed;
            font-size 13px;
            white-space nowrap
            transform translateX(-50%)

            span
                color #24BFFF

        .agreement
            .el-dialog__wrapper
                .el-dialog
                    .el-dialog__header
                        padding 10px

                        .el-dialog__title
                            font-size 16px
                            font-weight bold

                        .el-dialog__headerbtn
                            top: 10px
                            right 10px

                    .el-dialog__body
                        padding 0 10px 10px 10px
</style>
